package com.ruoyi.web.controller.user;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.CustomerUser;
import com.ruoyi.common.core.domain.entity.CustomerRegisterRequest;
import com.ruoyi.common.core.domain.entity.LoginVO;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ICustomerLoginUserService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.common.utils.MessageUtils;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.access.prepost.PreAuthorize;

@RestController
@RequestMapping("/user")
public class CustomerLoginController {
    @Autowired
    ICustomerLoginUserService customerLoginUserService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

    //注入 TokenService
    @Autowired
    private TokenService tokenService;

    // 短信验证码缓存键前缀
    private static final String SMS_CODE_KEY = "sms_code:";



    /*
    * 登录
    * */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginVO loginUser) {
        if(customerLoginUserService.login(loginUser)){
            AjaxResult ajax = AjaxResult.success();
            // 生成令牌
            String token = loginService.login(loginUser.getPhoneNumber(), loginUser.getPasswordHash(),loginUser.getCode(),loginUser.getUuid());
            ajax.put(Constants.TOKEN, token);
            return ajax;
        }
        return AjaxResult.error();
    }

    // 退出
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        System.out.println(loginUser);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除若依 sys_user 登录缓存（令牌）
            tokenService.delLoginUser(loginUser.getToken());
            System.out.println(loginUser.getToken());
            // 记录退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }
        return AjaxResult.success(MessageUtils.message("user.logout.success"));
    }

    /*
    * 注册
    * */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody CustomerRegisterRequest registerRequest) {
        // 验证必填字段
        if (StringUtils.isEmpty(registerRequest.getPhoneNumber())) {
            return AjaxResult.error("手机号不能为空");
        }
        if (StringUtils.isEmpty(registerRequest.getPassword())) {
            return AjaxResult.error("密码不能为空");
        }
        if (StringUtils.isEmpty(registerRequest.getConfirmPassword())) {
            return AjaxResult.error("确认密码不能为空");
        }
        if (StringUtils.isEmpty(registerRequest.getCode())) {
            return AjaxResult.error("验证码不能为空");
        }

        // 密码确认验证
        if (!registerRequest.getPassword().equals(registerRequest.getConfirmPassword())) {
            return AjaxResult.error("两次输入的密码不一致");
        }

        // 验证码验证
        String cacheKey = SMS_CODE_KEY + registerRequest.getPhoneNumber();
        Object cachedCode = redisTemplate.opsForValue().get(cacheKey);
        String code = null;
        if (cachedCode != null) {
             code = cachedCode.toString();
        }

        if (StringUtils.isEmpty(cacheKey)) {
            return AjaxResult.error("验证码已过期，请重新获取");
        }

        if (!code.equals(registerRequest.getCode())) {
            return AjaxResult.error("验证码错误");
        }

        // 验证码验证通过，删除缓存中的验证码
        redisTemplate.delete(cacheKey);

        // 构建CustomerUser对象
        CustomerUser customerUser = new CustomerUser();
        customerUser.setPhoneNumber(registerRequest.getPhoneNumber());
        customerUser.setPasswordHash(registerRequest.getPassword());
        customerUser.setNickname(registerRequest.getNickname());
        customerUser.setAvatarUrl(registerRequest.getAvatarUrl());
        customerUser.setGender(registerRequest.getGender());

        // 执行注册
        if (customerLoginUserService.register(customerUser)) {
            return AjaxResult.success("注册成功");
        }
        return AjaxResult.error("注册失败");
    }

    /**
     * 通过手机号查询客户ID（需权限）
     */
    @PreAuthorize("@ss.hasPermi('user:users:query')")
    @GetMapping("/getCustomerIdByPhone")
    public AjaxResult getCustomerIdByPhone(@RequestParam String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)) {
            return AjaxResult.error("手机号不能为空");
        }
        Long customerId = customerLoginUserService.getCustomerIdByPhone(phoneNumber);
        if (customerId == null) {
            return AjaxResult.error("用户不存在");
        }
        return AjaxResult.success(customerId);
    }
}
